﻿/**************************************************************
 * Copyright gt1987. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/5/9 14:56:19
 * Description: LeaderTaskSchedulerManager
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/
using log4net;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace gt.TaskScheduler.Core.Impl
{
    /// <summary>
    /// 集群Leader 任务调度管理器
    /// </summary>
    public class TaskSchedulerLeader : ITaskSchedulerLeader
    {
        private ITaskSchedulerMananger _manager;
        private string _name;

        public TaskSchedulerLeader(string name, ITaskSchedulerMananger manager)
        {
            _name = name;
            _manager = manager;

            _manager.RegisterLeader(_name);
            LogHelper.GetLogger().Info($"task scheduler leader: {_name} register.");
        }
        /// <summary>
        /// leader 运行
        /// </summary>
        /// <param name="taskNames"></param>
        public void Initialize(List<string> taskNames)
        {
            _manager.InitTaskQueue(taskNames);
            LogHelper.GetLogger().Info($"task scheduler init tasks,count: {taskNames.Count}.");

            _manager.MarkTaskSchedulerStatus(_name, TaskSchedulerStatus.Run);

            LogHelper.GetLogger().Info("task scheduler initialize ok.");
        }

        /// <summary>
        /// 监控任务调度集群各节点运行状态
        /// </summary>
        /// <returns></returns>
        public Task MonitTaskSchedulerMembers()
        {
            return Task.Run(() =>
            {
                while (true)
                {
                    if (_manager.CheckAllMembersFinished())
                    {
                        LogHelper.GetLogger().Info("all member has finished");
                        _manager.MarkTaskSchedulerStatus(_name, TaskSchedulerStatus.Stop);
                        break;
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(5000);
                    }
                }
            });
        }
    }
}
